package top.malaoshi.controller;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.bind.annotation.*;
import top.malaoshi.entity.Goods;
import top.malaoshi.model.JsonResult;
import top.malaoshi.service.GoodsSrvImpl;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class GoodsCtrl {

    @Resource
    private GoodsSrvImpl srv;

    @GetMapping("/goods/{id}")
    public JsonResult getById(@PathVariable String id){
        JsonResult res=new JsonResult(0,"success");
        Goods goods=srv.getById(id);
        if(goods==null){
            res.setCode(1);
            res.setMsg("数据不存在！");

        }else{
            try {
                Map map=BeanUtils.describe(goods);//传入java对象，返回Map
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String createTime=sdf.format(goods.getCreateTime());
                map.remove("class");
                map.put("createTime",createTime);
                res.setData(map);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        return res;
    }

    @GetMapping("/like/{id}")
    public JsonResult like(@PathVariable String id){
        JsonResult res=new JsonResult(0,"success");
        int like=srv.like(id,1);
        res.setData(like);
        return res;
    }
    @GetMapping("/cancelike/{id}")
    public JsonResult cancelike(@PathVariable String id){
        JsonResult res=new JsonResult(0,"success");
        int like=srv.like(id,-1);
        res.setData(like);
        return res;
    }

}
